const Router = require('koa-router')
const router = new Router()
const mysql = require('../../utils/mysql')
const log = require('../../utils/log')

router.get('/mysqlQueryAsync', async (ctx, next) => {
    await next()

    //这条语句没有带着数据库名字
    const sql = 'SELECT * FROM websites'

    let results = await mysql.query2(sql)
    console.log(results)

    ctx.body = {
        status: 'success',
        message: JSON.stringify(results)
    }
    await next()
})

router.get('/mysqlInsertAsync', async (ctx, next) => {
    const addSql = 'INSERT INTO websites(Id,name,url,alexa,country) VALUES(0,?,?,?,?)';
    const addSqlParams = ['菜鸟工具', 'https://c.runoob.com', '23453', 'CN'];

    let results = await mysql.query2(addSql, addSqlParams)
    //console.log(results)
    //记录日志
    log.info('mysqlInsertAsync: >', addSql + addSqlParams)

    ctx.body = {
        status: 'success',
        message: JSON.stringify(results)
    }
    await next()
})

router.get('/mysqlDeleteAsync/:id', async (ctx, next) => {
    id = ctx.params.id

    var delSql = 'DELETE FROM websites where id = ?'
    var delSqlParams = [id]

    let results = await mysql.query2(delSql, delSqlParams)

    //以下分别是删除 1 条 和 0 条记录的结果
    //{\"fieldCount\":0,\"affectedRows\":1,\"insertId\":0,\"serverStatus\":2,\"warningCount\":0,\"message\":\"\",\"protocol41\":true,\"changedRows\":0}"}
    //{\"fieldCount\":0,\"affectedRows\":0,\"insertId\":0,\"serverStatus\":2,\"warningCount\":0,\"message\":\"\",\"protocol41\":true,\"changedRows\":0}"}
    //记录日志
    log.info('mysqlDeleteAsync/' + id, delSql + delSqlParams)

    ctx.body = {
        status: 'success',
        message: JSON.stringify(results)
    }
    await next()
})


router.get('/mysqlUpdateAsync/:id', async (ctx, next) => {
    id = ctx.params.id

    var updateSql = 'UPDATE websites SET name = ?,url = ? WHERE Id = ?'
    var updateSqlParams = ['菜鸟移动站' + id, 'https://m.runoob.com', id]

    let results = await mysql.query2(updateSql, updateSqlParams)
    //console.log(results)
    //记录日志
    log.info('mysqlInsertAsync: >', updateSql + updateSqlParams)

    //以下分别是更新 1 条 和 0 条的结果
    //{"status":"success","message":"{\"fieldCount\":0,\"affectedRows\":1,\"insertId\":0,\"serverStatus\":2,\"warningCount\":0,\"message\":\"(Rows matched: 1  Changed: 1  Warnings: 0\",\"protocol41\":true,\"changedRows\":1}"}
    //{"status":"success","message":"{\"fieldCount\":0,\"affectedRows\":0,\"insertId\":0,\"serverStatus\":2,\"warningCount\":0,\"message\":\"(Rows matched: 0  Changed: 0  Warnings: 0\",\"protocol41\":true,\"changedRows\":0}"}
    ctx.body = {
        status: 'success',
        message: JSON.stringify(results)
    }

    await next()
})

module.exports = router